#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
学生社交媒体与人际关系数据集深度分析
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import warnings
warnings.filterwarnings('ignore')

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

class SocialMediaAnalyzer:
    def __init__(self, csv_path):
        """初始化分析器"""
        self.csv_path = csv_path
        self.df = None
        self.analysis_results = {}
        
    def load_data(self):
        """加载数据"""
        print("正在加载数据...")
        self.df = pd.read_csv(self.csv_path)
        print(f"数据加载完成！数据集形状: {self.df.shape}")
        return self.df
    
    def basic_info(self):
        """基本信息分析"""
        print("\n=== 数据集基本信息 ===")
        print(f"数据集大小: {self.df.shape[0]} 行, {self.df.shape[1]} 列")
        print(f"\n列名及数据类型:")
        for col in self.df.columns:
            print(f"- {col}: {self.df[col].dtype}")
        
        print(f"\n缺失值统计:")
        missing = self.df.isnull().sum()
        if missing.sum() > 0:
            print(missing[missing > 0])
        else:
            print("无缺失值")
        
        # 存储基本统计信息
        self.analysis_results['basic_stats'] = {
            'shape': self.df.shape,
            'missing_values': missing.to_dict(),
            'data_types': self.df.dtypes.to_dict()
        }
    
    def exploratory_analysis(self):
        """探索性数据分析"""
        print("\n=== 探索性数据分析 ===")
        
        # 数值变量统计
        numeric_cols = ['Age', 'Avg_Daily_Usage_Hours', 'Sleep_Hours_Per_Night', 
                       'Mental_Health_Score', 'Conflicts_Over_Social_Media', 'Addicted_Score']
        
        print("\n数值变量统计描述:")
        stats_desc = self.df[numeric_cols].describe()
        print(stats_desc)
        
        # 分类变量统计
        categorical_cols = ['Gender', 'Academic_Level', 'Country', 'Most_Used_Platform', 
                           'Affects_Academic_Performance', 'Relationship_Status']
        
        print("\n分类变量分布:")
        for col in categorical_cols:
            print(f"\n{col}:")
            value_counts = self.df[col].value_counts()
            print(value_counts.head(10))  # 显示前10个
        
        # 存储探索性分析结果
        self.analysis_results['descriptive_stats'] = stats_desc.to_dict()
        self.analysis_results['categorical_distributions'] = {}
        for col in categorical_cols:
            self.analysis_results['categorical_distributions'][col] = self.df[col].value_counts().to_dict()
    
    def correlation_analysis(self):
        """相关性分析"""
        print("\n=== 相关性分析 ===")
        
        # 数值变量相关性
        numeric_cols = ['Age', 'Avg_Daily_Usage_Hours', 'Sleep_Hours_Per_Night', 
                       'Mental_Health_Score', 'Conflicts_Over_Social_Media', 'Addicted_Score']
        
        correlation_matrix = self.df[numeric_cols].corr()
        print("\n数值变量相关性矩阵:")
        print(correlation_matrix)
        
        # 找出强相关关系
        strong_correlations = []
        for i in range(len(correlation_matrix.columns)):
            for j in range(i+1, len(correlation_matrix.columns)):
                corr_val = correlation_matrix.iloc[i, j]
                if abs(corr_val) > 0.5:  # 强相关阈值
                    strong_correlations.append({
                        'var1': correlation_matrix.columns[i],
                        'var2': correlation_matrix.columns[j],
                        'correlation': corr_val
                    })
        
        print("\n强相关关系 (|r| > 0.5):")
        for corr in strong_correlations:
            print(f"{corr['var1']} vs {corr['var2']}: {corr['correlation']:.3f}")
        
        self.analysis_results['correlations'] = {
            'matrix': correlation_matrix.to_dict(),
            'strong_correlations': strong_correlations
        }
    
    def hypothesis_testing(self):
        """假设检验和深入分析"""
        print("\n=== 假设检验与深入分析 ===")
        
        # 假设1: 社交媒体使用时间与学术表现的关系
        print("\n假设1: 社交媒体使用时间是否影响学术表现?")
        affected_group = self.df[self.df['Affects_Academic_Performance'] == 'Yes']['Avg_Daily_Usage_Hours']
        not_affected_group = self.df[self.df['Affects_Academic_Performance'] == 'No']['Avg_Daily_Usage_Hours']
        
        print(f"影响学术表现组平均使用时间: {affected_group.mean():.2f}小时")
        print(f"不影响学术表现组平均使用时间: {not_affected_group.mean():.2f}小时")
        
        # 假设2: 社交媒体使用与心理健康的关系
        print("\n假设2: 社交媒体使用时间与心理健康的关系")
        mental_health_corr = self.df['Avg_Daily_Usage_Hours'].corr(self.df['Mental_Health_Score'])
        print(f"使用时间与心理健康评分相关系数: {mental_health_corr:.3f}")
        
        # 假设3: 不同平台使用与成瘾程度的关系
        print("\n假设3: 不同社交媒体平台与成瘾程度的关系")
        platform_addiction = self.df.groupby('Most_Used_Platform')['Addicted_Score'].mean().sort_values(ascending=False)
        print("各平台平均成瘾评分:")
        print(platform_addiction)
        
        # 假设4: 恋爱关系状态与社交媒体冲突的关系
        print("\n假设4: 恋爱关系状态与社交媒体冲突的关系")
        relationship_conflicts = self.df.groupby('Relationship_Status')['Conflicts_Over_Social_Media'].mean()
        print("各关系状态平均冲突次数:")
        print(relationship_conflicts)
        
        # 假设5: 睡眠时间与社交媒体使用的关系
        print("\n假设5: 睡眠时间与社交媒体使用的关系")
        sleep_usage_corr = self.df['Sleep_Hours_Per_Night'].corr(self.df['Avg_Daily_Usage_Hours'])
        print(f"睡眠时间与使用时间相关系数: {sleep_usage_corr:.3f}")
        
        self.analysis_results['hypotheses'] = {
            'academic_performance': {
                'affected_avg_hours': affected_group.mean(),
                'not_affected_avg_hours': not_affected_group.mean()
            },
            'mental_health_correlation': mental_health_corr,
            'platform_addiction': platform_addiction.to_dict(),
            'relationship_conflicts': relationship_conflicts.to_dict(),
            'sleep_usage_correlation': sleep_usage_corr
        }
    
    def demographic_analysis(self):
        """人口统计学分析"""
        print("\n=== 人口统计学分析 ===")
        
        # 年龄分布分析
        print("\n年龄分布:")
        age_stats = self.df['Age'].describe()
        print(age_stats)
        
        # 性别分布
        print("\n性别分布:")
        gender_dist = self.df['Gender'].value_counts(normalize=True) * 100
        print(gender_dist)
        
        # 学历分布
        print("\n学历分布:")
        academic_dist = self.df['Academic_Level'].value_counts(normalize=True) * 100
        print(academic_dist)
        
        # 国家分布 (前10)
        print("\n国家分布 (前10):")
        country_dist = self.df['Country'].value_counts().head(10)
        print(country_dist)
        
        # 按性别分析社交媒体使用
        print("\n按性别分析社交媒体使用:")
        gender_usage = self.df.groupby('Gender')[['Avg_Daily_Usage_Hours', 'Addicted_Score', 'Mental_Health_Score']].mean()
        print(gender_usage)
        
        # 按学历分析社交媒体使用
        print("\n按学历分析社交媒体使用:")
        academic_usage = self.df.groupby('Academic_Level')[['Avg_Daily_Usage_Hours', 'Addicted_Score', 'Mental_Health_Score']].mean()
        print(academic_usage)
        
        self.analysis_results['demographics'] = {
            'age_stats': age_stats.to_dict(),
            'gender_distribution': gender_dist.to_dict(),
            'academic_distribution': academic_dist.to_dict(),
            'top_countries': country_dist.to_dict(),
            'gender_usage': gender_usage.to_dict(),
            'academic_usage': academic_usage.to_dict()
        }
    
    def platform_analysis(self):
        """社交媒体平台深度分析"""
        print("\n=== 社交媒体平台深度分析 ===")
        
        # 平台使用分布
        print("\n平台使用分布:")
        platform_dist = self.df['Most_Used_Platform'].value_counts()
        print(platform_dist)
        
        # 各平台用户特征分析
        print("\n各平台用户特征分析:")
        platform_analysis = self.df.groupby('Most_Used_Platform').agg({
            'Age': 'mean',
            'Avg_Daily_Usage_Hours': 'mean',
            'Mental_Health_Score': 'mean',
            'Addicted_Score': 'mean',
            'Sleep_Hours_Per_Night': 'mean',
            'Conflicts_Over_Social_Media': 'mean'
        }).round(2)
        print(platform_analysis)
        
        # 平台与学术表现的关系
        print("\n各平台对学术表现的影响:")
        platform_academic = pd.crosstab(self.df['Most_Used_Platform'], 
                                       self.df['Affects_Academic_Performance'], 
                                       normalize='index') * 100
        print(platform_academic)
        
        self.analysis_results['platform_analysis'] = {
            'distribution': platform_dist.to_dict(),
            'characteristics': platform_analysis.to_dict(),
            'academic_impact': platform_academic.to_dict()
        }
    
    def generate_insights(self):
        """生成洞察和结论"""
        print("\n=== 数据洞察与结论 ===")
        
        insights = []
        
        # 基于分析结果生成洞察
        
        # 1. 使用时间洞察
        avg_usage = self.df['Avg_Daily_Usage_Hours'].mean()
        high_usage_threshold = 6  # 定义高使用时间阈值
        high_usage_pct = (self.df['Avg_Daily_Usage_Hours'] > high_usage_threshold).mean() * 100
        
        insights.append({
            'category': '使用时间',
            'insight': f"学生平均每日社交媒体使用时间为{avg_usage:.1f}小时，{high_usage_pct:.1f}%的学生每日使用超过{high_usage_threshold}小时",
            'severity': 'high' if high_usage_pct > 30 else 'medium'
        })
        
        # 2. 心理健康洞察
        avg_mental_health = self.df['Mental_Health_Score'].mean()
        low_mental_health_pct = (self.df['Mental_Health_Score'] <= 5).mean() * 100
        
        insights.append({
            'category': '心理健康',
            'insight': f"学生平均心理健康评分为{avg_mental_health:.1f}/10，{low_mental_health_pct:.1f}%的学生心理健康评分较低(≤5分)",
            'severity': 'high' if low_mental_health_pct > 20 else 'medium'
        })
        
        # 3. 成瘾程度洞察
        avg_addiction = self.df['Addicted_Score'].mean()
        high_addiction_pct = (self.df['Addicted_Score'] >= 8).mean() * 100
        
        insights.append({
            'category': '成瘾风险',
            'insight': f"学生平均成瘾评分为{avg_addiction:.1f}/10，{high_addiction_pct:.1f}%的学生有高成瘾风险(≥8分)",
            'severity': 'high' if high_addiction_pct > 25 else 'medium'
        })
        
        # 4. 学术表现洞察
        academic_affected_pct = (self.df['Affects_Academic_Performance'] == 'Yes').mean() * 100
        
        insights.append({
            'category': '学术影响',
            'insight': f"{academic_affected_pct:.1f}%的学生认为社交媒体使用影响了他们的学术表现",
            'severity': 'high' if academic_affected_pct > 50 else 'medium'
        })
        
        # 5. 睡眠质量洞察
        avg_sleep = self.df['Sleep_Hours_Per_Night'].mean()
        poor_sleep_pct = (self.df['Sleep_Hours_Per_Night'] < 7).mean() * 100
        
        insights.append({
            'category': '睡眠质量',
            'insight': f"学生平均睡眠时间为{avg_sleep:.1f}小时，{poor_sleep_pct:.1f}%的学生睡眠不足(<7小时)",
            'severity': 'high' if poor_sleep_pct > 40 else 'medium'
        })
        
        print("\n关键洞察:")
        for i, insight in enumerate(insights, 1):
            print(f"{i}. 【{insight['category']}】{insight['insight']}")
        
        self.analysis_results['insights'] = insights
        
        return insights
    
    def run_full_analysis(self):
        """运行完整分析"""
        print("开始进行学生社交媒体与人际关系数据集深度分析...")
        print("=" * 60)
        
        # 加载数据
        self.load_data()
        
        # 运行各项分析
        self.basic_info()
        self.exploratory_analysis()
        self.correlation_analysis()
        self.demographic_analysis()
        self.platform_analysis()
        self.hypothesis_testing()
        insights = self.generate_insights()
        
        print("\n" + "=" * 60)
        print("分析完成！")
        
        return self.analysis_results

# 运行分析
if __name__ == "__main__":
    analyzer = SocialMediaAnalyzer('学生社交媒体与人际关系数据集/学生社交媒体与人际关系数据集.csv')
    results = analyzer.run_full_analysis()
